package com.leyou.search.listener;

import com.leyou.item.pojo.Spu;
import com.leyou.search.feign.GoodsClient;
import com.leyou.search.mapper.GoodsRepository;
import com.leyou.search.pojo.Goods;
import com.leyou.search.service.GoodsService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ItemListener {

    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    GoodsService goodsService;

    @Autowired
    GoodsClient goodsClient;



    // 进行数据绑定
    @RabbitListener(bindings = @QueueBinding(
            // 队列
            value = @Queue(value = "com.jiyun.leyou.queue2",durable = "true"),
            // 交换机的信息
            exchange =@Exchange(
                    value = "com.jiyun.leyou",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {"item.insert","item.update"}
    ))
    public void saveAndEdit(Long id) throws Exception {
        if(id==null){
            return;
        }
        // 不管是保存还是修改，最终的操作都是生成一个新的静态页面
        // spuID => goods
        Spu spu = goodsClient.getSpus(id);
        Goods goods = goodsService.buildGoods(spu);
        // save方法会进行智能判断  判断有没有id 如果有id 则修改 如果没有id 则添加
        goodsRepository.save(goods);
    }

    // 进行数据绑定
    @RabbitListener(bindings = @QueueBinding(
            // 队列
            value = @Queue(value = "com.jiyun.leyou.queue2",durable = "true"),
            // 交换机的信息
            exchange =@Exchange(
                    value = "com.jiyun.leyou",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {"item.delete"}
    ))
    public void delete(Long id){
        // 要把文件删除掉！！！
        if(id==null){
            return;
        }
        // goods对象的id是不是spu的id？
        goodsRepository.deleteById(id);

    }

}
